﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Models.NPOI;
using SHZY.DataEncryption;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.BaseData.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.BaseData.Entitys.Entity.Samplingplan;
using SHZY.BaseData.Entitys.Dto.Samplingplan;
using SHZY.BaseData.Entitys.Dto.QmsBaseDefect;
using Microsoft.AspNetCore.Http;
using SHZY.BaseData.Entitys;
using SHZY.Common.Helper;
using SHZY.Common.Core.Manager.Files;

namespace SHZY.BaseData;

/// <summary>
/// 业务实现：抽样方案.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "Samplingplan", Order = 200)]
[Route("api/BaseData/[controller]")]
public class QmsBaseSamplingplanService : IQmsBaseSamplingplanService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBaseSamplingplanEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 文件管理.
    /// </summary>
    private readonly IFileManager _fileManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBaseSamplingplanService"/>类型的新实例.
    /// </summary>
    public QmsBaseSamplingplanService(
        ISqlSugarRepository<QmsBaseSamplingplanEntity> qmsBaseSamplingplanRepository,
        ISqlSugarClient context,
        IUserManager userManager,
        IFileManager fileManager)
    {
        _repository = qmsBaseSamplingplanRepository;
        _db = context.AsTenant();
        _userManager = userManager;
        _fileManager = fileManager;
    }

    /// <summary>
    /// 获取抽样方案.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        var output = (await _repository.FirstOrDefaultAsync(x => x.Id == id))
            .Adapt<QmsBaseSamplingplanInfoOutput>();

        var qmsBaseSamplingplandetailList = await _repository.Context
            .Queryable<QmsBaseSamplingplandetailEntity>()
            .Where(w => w.MainId == output.id)
            .ToListAsync();

        output.qmsBaseSamplingplandetailList = qmsBaseSamplingplandetailList
            .Adapt<List<QmsBaseSamplingplandetailInfoOutput>>();

        return output;
    }

    /// <summary>
    /// 获取所有启用的抽样方案列表.
    /// </summary>
    /// <returns></returns>
    [HttpGet("All")]
    public async Task<dynamic> GetListAll()
    {
        var data = await _repository.AsQueryable()
            .InnerJoin<QmsBaseSamplingplandetailEntity>((x, b) => x.Id == b.MainId)
            .Where(x => x.DeleteMark == null && x.EnabledMark == 1)
            .OrderBy(x => x.Name)
            .Select((x, b) => new { SamplingPlan = x, SamplingplanDetail = b })
            .ToListAsync();

        var result = data.GroupBy(g => g.SamplingPlan.Id).Select(s =>
        {
            var output = s.First().SamplingPlan.Adapt<QmsBaseSamplingplanInfoOutput>();
            output.qmsBaseSamplingplandetailList = s.Select(s1 => s1.SamplingplanDetail)
            .Adapt<List<QmsBaseSamplingplandetailInfoOutput>>();
            return output;
        }).ToList();

        return result;
    }

    /// <summary>
    /// 获取抽样方案列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBaseSamplingplanListQueryInput input)
    {
        var data = await _repository.Context.Queryable<QmsBaseSamplingplanEntity>()
            .Where(it => it.DeleteMark == null)
            .WhereIF(!string.IsNullOrEmpty(input.name), it => it.Name.Contains(input.name))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Name.Contains(input.keyword))
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Select(it => new QmsBaseSamplingplanListOutput
            {
                id = it.Id,
                name = it.Name,
                creatorUserId = it.CreatorUserId,
                creatorTime = it.CreatorTime,
                lastModifyUserId = it.LastModifyUserId,
                lastModifyTime = it.LastModifyTime,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "无效", "有效"),
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort)
            .ToPagedListAsync(input.currentPage, input.pageSize);

        return PageResult<QmsBaseSamplingplanListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建抽样方案.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBaseSamplingplanCrInput input)
    {
        if (await _repository.AnyAsync(x => (x.Name == input.name) && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);

        var entity = input.Adapt<QmsBaseSamplingplanEntity>();
        entity.CreatorUserId = _userManager.UserId;
        entity.CreatorTime = DateTime.Now;

        try
        {
            // 开启事务
            _db.BeginTran();

            var newEntity = await _repository.Context
                .Insertable<QmsBaseSamplingplanEntity>(entity)
                .IgnoreColumns(ignoreNullColumn: true)
                .CallEntityMethod(m => m.Creator())
                .ExecuteReturnEntityAsync();

            var qmsBaseSamplingplandetailEntityList = input.qmsBaseSamplingplandetailList.Adapt<List<QmsBaseSamplingplandetailEntity>>();
            if (qmsBaseSamplingplandetailEntityList.Count() > 0)
            {
                foreach (var item in qmsBaseSamplingplandetailEntityList)
                {
                    //item.Id = SnowflakeIdHelper.NextId();
                    item.MainId = newEntity.Id;
                }

                await _repository.Context
                    .Insertable<QmsBaseSamplingplandetailEntity>(qmsBaseSamplingplandetailEntityList)
                    .CallEntityMethod(m => m.Creator())
                    .ExecuteCommandAsync();
            }

            // 关闭事务
            _db.CommitTran();
        }
        catch (Exception)
        {
            // 回滚事务
            _db.RollbackTran();

            throw Oops.Oh(ErrorCode.COM1000);
        }
    }

    /// <summary>
    /// 获取抽样方案无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] QmsBaseSamplingplanListQueryInput input)
    {
        return await _repository.Context.Queryable<QmsBaseSamplingplanEntity>()
            .InnerJoin<QmsBaseSamplingplandetailEntity>((it, b) => it.Id == b.MainId)
            .Where(it => it.DeleteMark == null)
            .WhereIF(!string.IsNullOrEmpty(input.name), it => it.Name.Contains(input.name))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Name.Contains(input.keyword))
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Select(it => new QmsBaseSamplingplanListOutput
            {
                id = it.Id,
                name = it.Name,
                creatorUserId = it.CreatorUserId,
                creatorTime = it.CreatorTime,
                lastModifyUserId = it.LastModifyUserId,
                lastModifyTime = it.LastModifyTime,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "无效", "有效"),
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToListAsync();
    }

    /// <summary>
    /// 导出抽样方案.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] QmsBaseSamplingplanListQueryInput input)
    {
        var exportData = new List<QmsBaseSamplingplanListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBaseSamplingplanListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"抽样方案名称\",\"field\":\"name\"},{\"value\":\"创建人\",\"field\":\"creatorUserId\"},{\"value\":\"创建时间\",\"field\":\"creatorTime\"},{\"value\":\"更新人\",\"field\":\"lastModifyUserId\"},{\"value\":\"更新时间\",\"field\":\"lastModifyTime\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "抽样⽅案.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = Path.Combine(FileVariable.TemporaryFilePath, excelconfig.FileName);
        ExcelExportHelper<QmsBaseSamplingplanListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 批量删除抽样方案.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<QmsBaseSamplingplanEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                _ = await _repository.Context
               .Updateable<QmsBaseSamplingplanEntity>()
               .SetColumns(it => new QmsBaseSamplingplanEntity()
               {
                   DeleteTime = DateTime.Now,
                   DeleteMark = 1,
                   DeleteUserId = _userManager.UserId
               }).Where(it => ids.Contains(it.Id))
               .ExecuteCommandHasChangeAsync();

                _ = await _repository.Context
              .Updateable<QmsBaseSamplingplandetailEntity>()
              .SetColumns(it => new QmsBaseSamplingplandetailEntity()
              {
                  DeleteTime = DateTime.Now,
                  DeleteMark = 1,
                  DeleteUserId = _userManager.UserId
              }).Where(it => ids.Contains(it.MainId))
              .ExecuteCommandHasChangeAsync();

                // 批量删除抽样方案
                // await _repository.Context.Deleteable<QmsBaseSamplingplanEntity>().In(it => it.Id, ids).ExecuteCommandAsync();

                // 清空抽样方案子表表数据
                // await _repository.Context.Deleteable<QmsBaseSamplingplandetailEntity>().In(u => u.MainId, entitys.Select(s => s.Id).ToArray()).ExecuteCommandAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();
                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }

    /// <summary>
    /// 更新抽样方案.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] QmsBaseSamplingplanUpInput input)
    {
        if (await _repository.AnyAsync(x => (x.Name == input.name) && x.DeleteMark == null && x.Id != input.id))
            throw Oops.Oh(ErrorCode.COM1004);

        var entity = input.Adapt<QmsBaseSamplingplanEntity>();
        entity.LastModifyUserId = _userManager.UserId;
        entity.LastModifyTime = DateTime.Now;
        try
        {
            // 开启事务
            _db.BeginTran();

            await _repository.Context
                .Updateable<QmsBaseSamplingplanEntity>(entity)
                .IgnoreColumns(ignoreAllNullColumns: true)
                .CallEntityMethod(m => m.LastModify())
                .ExecuteCommandAsync();

            // 清空抽样方案子表原有数据
            await _repository.Context.Deleteable<QmsBaseSamplingplandetailEntity>().Where(it => it.MainId == entity.Id).ExecuteCommandAsync();

            // 新增抽样方案子表新数据
            var qmsBaseSamplingplandetailEntityList = input.qmsBaseSamplingplandetailList.Adapt<List<QmsBaseSamplingplandetailEntity>>();
            if (qmsBaseSamplingplandetailEntityList.Count()>0)
            {
                foreach (var item in qmsBaseSamplingplandetailEntityList)
                {
                    //item.Id = SnowflakeIdHelper.NextId();
                    item.MainId = entity.Id;
                }

                await _repository.Context
                    .Insertable<QmsBaseSamplingplandetailEntity>(qmsBaseSamplingplandetailEntityList)
                    .CallEntityMethod(m => m.Creator())
                    .ExecuteCommandAsync();
            }

            // 关闭事务
            _db.CommitTran();
        }
        catch (Exception)
        {
            // 回滚事务
            _db.RollbackTran();
            throw Oops.Oh(ErrorCode.COM1001);
        }
    }

    /// <summary>
    /// 删除抽样方案.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        if (!await _repository.Context.Queryable<QmsBaseSamplingplanEntity>().AnyAsync(it => it.Id == id))
        {
            throw Oops.Oh(ErrorCode.COM1005);
        }

        try
        {
            // 开启事务
            _db.BeginTran();

            _ = await _repository.Context.Updateable<QmsBaseSamplingplanEntity>()
            .SetColumns(it => new QmsBaseSamplingplanEntity()
            {
                DeleteTime = DateTime.Now,
                DeleteMark = 1,
                DeleteUserId = _userManager.UserId
            }).Where(x => x.Id == id)
            .ExecuteCommandHasChangeAsync();

            _ = await _repository.Context.Updateable<QmsBaseSamplingplandetailEntity>()
            .SetColumns(it => new QmsBaseSamplingplandetailEntity()
            {
                DeleteTime = DateTime.Now,
                DeleteMark = 1,
                DeleteUserId = _userManager.UserId
            }).Where(x => x.MainId == id)
            .ExecuteCommandHasChangeAsync();

            //if (!isOk) throw Oops.Oh(ErrorCode.COM1002);
            //var entity = await _repository.AsQueryable().FirstAsync(it => it.Id.Equals(id));
            //await _repository.Context.Deleteable<QmsBaseSamplingplanEntity>().Where(it => it.Id.Equals(id)).ExecuteCommandAsync();
            //// 清空抽样方案子表表数据
            //await _repository.Context.Deleteable<QmsBaseSamplingplandetailEntity>().Where(it => it.MainId.Equals(entity.Id)).ExecuteCommandAsync();

            // 关闭事务
            _db.CommitTran();
        }
        catch (Exception)
        {
            // 回滚事务
            _db.RollbackTran();

            throw Oops.Oh(ErrorCode.COM1002);
        }
    }

    /// <summary>
    /// 上传文件.
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost("Uploader")]
    public async Task<dynamic> Uploader(IFormFile file)
    {
        try
        {
            var _filePath = _fileManager.GetPathByType(string.Empty);
            var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + SnowflakeIdHelper.NextId() + Path.GetExtension(file.FileName);
            var stream = file.OpenReadStream();
            await _fileManager.UploadFileByType(stream, _filePath, _fileName);
            return new { name = _fileName, url = string.Format("/api/File/Image/{0}/{1}", string.Empty, _fileName) };

        }
        catch (Exception)
        {
            throw Oops.Oh(ErrorCode.D8001);
        }
    }

    /// <summary>
    /// 导入数据.
    /// </summary>
    /// <param name="input">请求参数</param>
    /// <returns></returns>
    [HttpPost("ImportData")]
    public async Task<dynamic> ImportData([FromBody] QmsBaseDefectImportDataInput input)
    {
        var output = new QmsBaseDefectImportDataOutput();
        foreach (var item in input.list)
        {
            try
            {
                if (await _repository.AnyAsync(x => (x.Name == item.name) && x.DeleteMark == null))
                    throw Oops.Oh(ErrorCode.COM1004);

                var entity = item.Adapt<QmsBaseDefectEntity>();

                var isOK = await _repository.Context.Insertable(entity).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOK < 1)
                {
                    output.failResult.Add(item);
                    output.fnum++;
                }
                else
                {
                    output.snum++;
                }
            }
            catch (Exception ex)
            {
                item.exceptionMsg = ex.Message;
                output.failResult.Add(item);
                output.fnum++;
            }
        }
        if (output.snum == input.list.Count)
        {
            output.resultType = 1;
        }
        else
        {
            output.resultType = 0;
        }
        return output;
    }

    /// <summary>
    /// 模板下载.
    /// </summary>
    /// <returns></returns>
    [HttpGet("TemplateDownload")]
    public async Task<dynamic> TemplateDownload()
    {
        string _fileName = "抽样方案模板.xlsx";
        var filePath = Path.Combine(FileVariable.TemplateFilePath, "Samplingplan_import_template.xlsx"); // 模板路径
        var addFilePath = Path.Combine(FileVariable.TemplateFilePath, _fileName); // 保存路径
        if (!(await _fileManager.ExistsFile(addFilePath)))
        {
            var stream = await _fileManager.GetFileStream(filePath);
            await _fileManager.UploadFileByType(stream, FileVariable.TemporaryFilePath, _fileName);
        }

        return new { name = _fileName, url = "/api/file/Download?encryption=" + DESCEncryption.Encrypt(_userManager.UserId + "|" + _fileName, "SHZY") };
    }

    /// <summary>
    /// 导入预览.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    [HttpGet("ImportPreview")]
    public async Task<dynamic> ImportPreview(string fileName)
    {
        try
        {
            var filePath = FileVariable.TemporaryFilePath;
            var savePath = Path.Combine(filePath, fileName);
            // 得到数据
            var sr = await _fileManager.GetFileStream(savePath);
            var excelData = ExcelImportHelper.ToDataTable(savePath, sr);
            foreach (var item in excelData.Columns)
            {
                excelData.Columns[item.ToString()].ColumnName = GetFileEncode(item.ToString());
            }
            // 删除文件
            await _fileManager.DeleteFile(savePath);
            // 返回结果
            return new { dataRow = excelData };
        }
        catch (Exception)
        {

            throw Oops.Oh(ErrorCode.D1801);
        }
    }

    /// <summary>
    /// 获取字段编码.
    /// </summary>
    /// <param name="filed"></param>
    /// <returns></returns>
    private string GetFileEncode(string filed)
    {
        throw new NotImplementedException();

        //switch (filed)
        //{
        //    case "缺陷类别名称":
        //        return "Name";
        //    case "默认严重度":
        //    case "默认严重度（字典项：高中低）":
        //    case "默认严重度（字典项：高：tall 中：centre 低：low）":
        //        return "Severity";
        //    case "备注":
        //        return "Remarks";
        //    default:
        //        return string.Empty;
        //}
    }
}